using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using WYD.Common;
using WYD.Infrastructure.Attribute;
using WYD.Infrastructure.Controllers;
using WYD.Infrastructure.Enums;
using WYD.Infrastructure.ExceptionImpl;
using WYD.Infrastructure.Model;
using WYD.Infrastructure.WebExtensions;
using WYD.ServiceCore.Filters;
using WYD.ServiceCore.Model;
using WYD.ServiceCore.Model.Dto;
using WYD.ServiceCore.Services.IService;

namespace WYD.Admin.WebApi.Controllers.System
{
    /// <summary>
    /// 个人中心
    /// </summary>
    [Verify]
    [Route("system/user/profile")]
    [ApiExplorerSettings(GroupName = "sys")]
    public class SysProfileController : BaseController
    {
        private readonly ISysUserService _userService;
        private readonly ISysRoleService _roleService;
        private readonly ISysUserPostService _userPostService;
        private readonly ISysDeptService _deptService;
        private readonly ISysFileService _fileService;
        private IWebHostEnvironment _hostEnvironment;
        private readonly OptionsSetting _optionsSetting;
        private readonly ISysPermissionService _sysPermissionService;

        public SysProfileController(
            ISysUserService userService,
            ISysRoleService roleService,
            ISysUserPostService postService,
            ISysDeptService deptService,
            ISysFileService sysFileService,
            IWebHostEnvironment hostEnvironment,
            IOptions<OptionsSetting> options, 
            ISysPermissionService sysPermissionService)
        {
            _userService = userService;
            _roleService = roleService;
            _userPostService = postService;
            _deptService = deptService;
            _fileService = sysFileService;
            this._hostEnvironment = hostEnvironment;
            _sysPermissionService = sysPermissionService;
            _optionsSetting = options.Value;
        }

        /// <summary>
        /// 个人中心用户信息获取
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Profile()
        {
            long userId = HttpContext.GetUId();
            var user = _userService.SelectUserById(userId);

            var roles = _roleService.SelectUserRoleNames(userId);
            var permissions = _sysPermissionService.GetMenuPermission(user);
            var postGroup = _userPostService.GetPostsStrByUserId(userId);
            var deptInfo = _deptService.GetFirst(f => f.DeptId == user.DeptId);
            user.DeptName = deptInfo?.DeptName ?? "-";

            return SUCCESS(new { user, roles, permissions, postGroup }, TIME_FORMAT_FULL);
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [ActionPermissionFilter(Permission = "common")]
        [Log(Title = "修改信息", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateProfile([FromBody] SysUserDto userDto)
        {
            if (userDto == null)
            {
                throw new CustomException(ResultCode.PARAM_ERROR, "请求参数错误");
            }
            var user = userDto.Adapt<SysUser>().ToUpdate(HttpContext);

            int result = _userService.ChangeUser(user);
            return ToResponse(result);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPut("updatePwd")]
        [ActionPermissionFilter(Permission = "common")]
        [Log(Title = "修改密码", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdatePwd(string oldPassword, string newPassword)
        {
            long userId = HttpContext.GetUId();
            var user = _userService.SelectUserById(userId);
            string oldMd5 = Tools.GetMd5Hash(oldPassword);
            string newMd5 = Tools.GetMd5Hash(newPassword);

            if (!user.Password.Equals(oldMd5, StringComparison.OrdinalIgnoreCase))
            {
                return ToResponse(ApiResult.Error("修改密码失败，旧密码错误"));
            }
            if (user.Password.Equals(newMd5, StringComparison.OrdinalIgnoreCase))
            {
                return ToResponse(ApiResult.Error("新密码不能和旧密码相同"));
            }
            if (_userService.ResetPwd(userId, newMd5) > 0)
            {
                //TODO 更新缓存

                return SUCCESS(1);
            }

            return ToResponse(ApiResult.Error("修改密码异常，请联系管理员"));
        }

        // /// <summary>
        // /// 修改头像
        // /// </summary>
        // /// <param name="formFile"></param>
        // /// <returns></returns>
        // [HttpPost("avatar")]
        // [ActionPermissionFilter(Permission = "common")]
        // [Log(Title = "修改头像", BusinessType = BusinessType.UPDATE, IsSaveRequestData = false)]
        // public IActionResult Avatar([FromForm(Name = "picture")] IFormFile formFile)
        // {
        //     long userId = HttpContext.GetUId();
        //     if (formFile == null) throw new CustomException("请选择文件");
        //     
        //     //TODO
        //     // var file = await FileService.SaveFileToLocal(hostEnvironment.WebRootPath, "", "avatar", 
        //     //     HttpContext.GetUId(), HttpContext.GetName(), formFile, _optionsSetting.Upload.UploadUrl);
        //     var file = new SysFile();
        //
        //     _userService.UpdatePhoto(new SysUser { Avatar = file.AccessUrl, UserId = userId });
        //     return SUCCESS(new { imgUrl = file.AccessUrl });
        // }
    }
}
